package com.haotian.encrypt;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * DesEdeUtils
 * <p>
 * </p>
 * 
 * @author : 张昊天
 * @date : 2017年9月7日
 */
public class DesEdeUtils {

	private final String Algorithm = "DesEdeUtils";
	private String charset;
	private SecretKey key;

	/**
	 * @param desKey
	 *            算法密钥 长度24字节
	 */
	public DesEdeUtils(byte[] desKey, String charset) {
		if (desKey.length != 24)
			throw new RuntimeException("密钥长度错误");
		this.charset = charset;
		key = new SecretKeySpec(desKey, Algorithm);
	}

	public byte[] encode(String data) throws Exception {
		return doFinal(Cipher.ENCRYPT_MODE, data.getBytes(charset));
	}

	public String encodeToBase64(String data) throws Exception {
		byte[] buf = doFinal(Cipher.ENCRYPT_MODE, data.getBytes(charset));
		return Base64.encodeBase64String(buf);
	}

	public byte[] decode(byte[] data) throws Exception {
		return doFinal(Cipher.DECRYPT_MODE, data);
	}

	public byte[] decode(String base64Des) throws Exception {
		return doFinal(Cipher.DECRYPT_MODE, Base64.decodeBase64(base64Des));
	}

	public String decodeToString(byte[] data) throws Exception {
		byte[] buf = doFinal(Cipher.DECRYPT_MODE, data);
		return new String(buf, charset);
	}

	public String decodeToString(String base64Des) throws Exception {
		byte[] data = Base64.decodeBase64(base64Des);
		byte[] buf = doFinal(Cipher.DECRYPT_MODE, data);
		return new String(buf, charset);
	}

	private byte[] doFinal(int cipherMode, byte[] data) throws Exception {
		// 可信任的随机数源
		SecureRandom sr = new SecureRandom();
		// 根据mode 创建 加密 或 解密对象
		Cipher cipher = Cipher.getInstance(Algorithm);
		cipher.init(cipherMode, key, sr);
		// 把字符串解码为字节数组，并解密
		return cipher.doFinal(data);
	}

}
